<?php
namespace app\index\controller;

use think\Controller;
use think\Request;
use think\Exception;
use sms\Sms as jysms;
use sms\Smsll as llsms;

class Sms extends Base
{
    // 短信模板列表
    public function modeList()
    {
        $data = input();//rows page
        $where = [];
        if (isset($data['status'])) {
            $where['status'] = $data['status'];
        }
        $modeList = db('crm_sms_content')->where($where)->limit(($data['page']-1)*$data['rows'],$data['rows'])->order('date DESC')->select();

        $count = db('crm_sms_content')->where($where)->count();

        apiReturn(200,'获取成功',['list'=>$modeList,'count'=>$count]);
    }

    // 发送短信
    public function sendSms()
    {
        $data = input();//client_ids modeId

        if (!isset($data['client_ids']) && !isset($data['modeId'])) {
            apiReturn(201,'参数不能为空');
        }

        $client_ids = explode(',', $data['client_ids']);
        $failedPhone = [];
        $modeContent = db('crm_sms_content')->where('modeId',$data['modeId'])->value('content');
        $manage_author = $this->getManageAuthor();
        foreach ($client_ids as $key => $value) {
            // $phone = db('crm_customer')->where('client_id',$value)->value('phone');
            if ($key == 0) {
                $phone = '15270826615';
                $result = jysms::send($phone, $data['modeId']);
                if (!$result) {
                    $failedPhone[] = $phone;
                }else{
                    $this->followAdd($value, $manage_author['username'], '发送短信', '短信内容：'.$modeContent);
                }
            }
        }
        if (empty($failedPhone)) {
            apiReturn(200,'发送成功');
        }else{
            apiReturn(201,'发送失败电话：'.implode(',', $failedPhone));
        }
    }

    // 联鹿创建短信签名
    public function createSign()
    {
        $data = input();//content
        if (empty($data['content'])) {
            apiReturn(201,'参数不能为空');
        }
        $result = llsms::createSign($data['content']);//81648
        apiReturn(200,'创建成功');
    }

    // 联鹿短信签名查询
    public function signInfo()
    {
        $result = llsms::signInfo();
        apiReturn(200,'获取成功',$result);
    }

    // 删除短信签名
    public function signDelete()
    {
        $SignId = input('id');
        if (empty($SignId)) {
            apiReturn(201,'参数不能为空');
        }
        $result = llsms::signDelete($SignId);
        apiReturn(200,'删除成功');
    }

    // 联鹿创建短信模板
    public function createTemplate()
    {
        $data = input();//type signId content
        if (!isset($data['type']) || !isset($data['signId']) || !isset($data['content'])) {
            apiReturn(201,'参数不完整');
        }
        $result = llsms::createTemplate($data['type'], $data['signId'], $data['content']);//70051516
        apiReturn(200,'创建成功');
    }

    // 联鹿短信模板查询
    public function templateInfo()
    {
        $result = llsms::templateInfo('70051516');
        apiReturn(200,'获取成功',$result);
    }

    // 短信模板列表查询
    public function templateList()
    {
        $data = input();//type
        if (!isset($data['type'])) {
            apiReturn(201,'参数不完整');
        }
        $result = llsms::templateList($data['type']);
        apiReturn(200,'获取成功',$result);
    }

    // 删除短信模板
    public function templateDelete()
    {
        $data = input();//type TemplateId
        if (!isset($data['type']) || !isset($data['TemplateId'])) {
            apiReturn(201,'参数不完整');
        }
        $result = llsms::templateDelete($data['type'], $data['TemplateId']);
        apiReturn(200,'删除成功');
    }

    // 联鹿模板短信发送
    public function templateSend()
    {
        try {
            $data = input();//type TemplateId PhoneNumberSet TemplateParamSet templateContent
            if (!isset($data['type']) || !isset($data['TemplateId']) || !isset($data['TemplateParamSet']) || !isset($data['PhoneNumberSet']) || !isset($data['templateContent'])) {
                apiReturn(201,'参数不完整');
            }
            $manage_author = $this->getManageAuthor();
            $PhoneNumberSet = explode(',', $data['PhoneNumberSet']);
            if (strpos($manage_author['group_name'],'教务经理')) {
                $max_number = 3000;
            }else{
                $max_number = 300;
            }
            self::smsNumberCheck($manage_author['username'], count($PhoneNumberSet), $max_number);
            $taskId = llsms::templateSend($data['type'], $data['TemplateId'], $data['TemplateParamSet'], $PhoneNumberSet);
            self::smsRecordNew($data['type'], $manage_author['username'], $PhoneNumberSet, $data['templateContent'], implode(',', $data['TemplateParamSet']), $taskId);
        } catch (Exception $e) {
            apiReturn(201,$e->getMessage());
        }
        // foreach ($PhoneNumberSet as $key => $value) {
        //     self::smsRecord($data['type'], $manage_author['username'], $value, $data['templateContent'], implode(',', $data['TemplateParamSet']));
        // }
        apiReturn(200,'发送成功',$taskId);
    }

    // 普通短信发送
    public function normalSend()
    {
        $data = input();//type content PhoneNumberSet
        if (!isset($data['type']) || !isset($data['content']) || !isset($data['PhoneNumberSet'])) {
            apiReturn(201,'参数不完整');
        }
        $contentLength = mb_strlen($data['content']);
        if ($contentLength > 50) {
            apiReturn(201,'字数不可超过50个');
        }
        $manage_author = $this->getManageAuthor();
        $PhoneNumberSet = explode(',', $data['PhoneNumberSet']);
        if (strpos($manage_author['group_name'],'教务经理')) {
            $max_number = 3000;
        }else{
            $max_number = 300;
        }
        self::smsNumberCheck($manage_author['username'], count($PhoneNumberSet), $max_number);
        if ($data['type'] == 2) {
            $data['content'] = $data['content'].'，拒收请回复R。';
        }
        $taskId = llsms::normalSend($data['type'], $data['content'], $PhoneNumberSet);
        self::smsRecordNew($data['type'], $manage_author['username'], $PhoneNumberSet, $data['content'], '', $taskId);
        // foreach ($PhoneNumberSet as $key => $value) {
        //     self::smsRecord($data['type'], $manage_author['username'], $value, $data['content'], '');
        // }
        apiReturn(200,'发送成功',$taskId);
    }

    // 当日短信数量验证
    public function smsNumberCheck($manage_id, $number, $max_number = 0)
    {
        if (empty($manage_id) || empty($number)) {
            apiReturn(201,'参数错误');
        }
        $starttime = date('Y-m-d 00:00:00',time());
        $endtime = date('Y-m-d 23:59:59',time());
        $where['date'] = array(array('egt',strtotime($starttime)),array('elt',strtotime($endtime)));
        $where['manage_id'] = $manage_id;
        $count = db('crm_sms_record')->where($where)->count();
        if (empty($max_number)) {
            $max_number = 300;
        }
        if (($count + $number) > $max_number) {
            apiReturn(201,'当日可发送短信数量为'.$max_number.'条，当前已发送'.$count.'条');
        }else{
            return true;
        }
    }

    // 余额查询
    public function productBalance()
    {
        $number1 = llsms::productBalance(1);
        $number2 = llsms::productBalance(2);
        apiReturn(200,'获取成功',['number1'=>$number1,'number2'=>$number2]);
    }

    // 拉取报告API
    public function report()
    {
        $string = '亲爱的家长，您购买的课程3元记忆力课程周二周三晚上7点就要开课了，请您添加老师微信（19100199152），以免错过重要消息';
        var_dump(mb_strlen($string));exit;
        $result = llsms::report(2, '202311101015130025132');
        var_dump($result);
        // array(4) {
        //   ["data"]=>
        //   array(1) {
        //     [0]=>
        //     array(7) {
        //       ["sequenceId"]=>
        //       string(9) "211061549"
        //       ["phone"]=>
        //       string(11) "13767541211"
        //       ["content"]=>
        //       string(177) "【学想教育】家长您好，我是学想教育胡永棠老师，您报名的课程即将开课，请加我做好课前准备，微信搜索15270826615，拒收请回复R。"
        //       ["status"]=>
        //       string(1) "1"
        //       ["respTime"]=>
        //       string(19) "2023-11-10 15:13:58"
        //       ["respCode"]=>
        //       string(7) "DELIVRD"
        //       ["tag"]=>
        //       string(0) ""
        //     }
        //   }
        //   ["message"]=>
        //   string(7) "success"
        //   ["timestamp"]=>
        //   int(1699603483059)
        //   ["status"]=>
        //   string(2) "00"
        // }
    }

    //设置销售短信参数
    public function setSmsParam()
    {
        $data = input();//name phone weixin
        if (!isset($data['name']) || !isset($data['phone']) || !isset($data['weixin'])) {
            apiReturn(201,'参数不完整');
        }
        $manage_author = $this->getManageAuthor();
        $data['manage_id'] = $manage_author['username'];
        $exist = db('crm_sms_param')->where('manage_id',$manage_author['username'])->find();
        if ($exist) {
            db('crm_sms_param')->where('manage_id',$manage_author['username'])->update($data);
        }else{
            $data['date'] = time();
            db('crm_sms_param')->insert($data);
        }
        apiReturn(200,'设置成功');
    }

    // 获取短信参数
    public function getSmsParam()
    {
        $manage_author = $this->getManageAuthor();
        $info = db('crm_sms_param')->where('manage_id',$manage_author['username'])->find();
        apiReturn(200,'获取成功',$info);
    }

    // 短信记录
    public function smsRecord($type, $manage_id, $phone, $content, $TemplateParamSet, $taskId = '')
    {
        if (!isset($type) || !isset($manage_id) || !isset($phone) || !isset($content)) {
            apiReturn(201,'记录参数不完整');
        }
        $datas = [
            'type'=>$type,
            'manage_id'=>$manage_id,
            'phone'=>$phone,
            'content'=>$content,
            'param'=>$TemplateParamSet,
            'date'=>time(),
            'task_id'=>$taskId
        ];
        db('crm_sms_record')->insert($datas);
        return true;
    }

    // 批量新增短信记录
    public function smsRecordNew($type, $manage_id, $phones, $content, $TemplateParamSet, $taskId = '')
    {
        if (!isset($type) || !isset($manage_id) || !isset($phones) || !isset($content)) {
            apiReturn(201,'记录参数不完整');
        }
        if (!is_array($phones)) {
            $phones = explode(',', $phones);
        }
        $datas = [];
        foreach ($phones as $key => $value) {
            $datas[] = [
                'type'=>$type,
                'manage_id'=>$manage_id,
                'phone'=>$value,
                'content'=>$content,
                'param'=>$TemplateParamSet,
                'date'=>time(),
                'task_id'=>$taskId
            ];
        }
        db('crm_sms_record')->insertAll($datas);
        return true;
    }

    // 短信记录列表
    public function smsRecordList()
    {
        $data = input();//phone
        if (!isset($data['phone'])) {
            apiReturn(201,'参数不完整');
        }
        $list = db('crm_sms_record')->alias('a')->join('tp_crm_manage b','a.manage_id=b.username')->field('a.*,b.name as manage_name')->where('a.phone',$data['phone'])->order('a.date DESC')->select();
        apiReturn(200,'获取成功',$list);
    }

}
?>